package com.longyi.admin.aspect;

import com.longyi.admin.annotation.Logging;
import com.longyi.admin.common.TokenUtil;
import com.longyi.admin.entity.Log;
import com.longyi.admin.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.List;

@Aspect
@Component
@Slf4j
public class LogAspect {
    @Autowired
    private LogService logService;
    
    @Pointcut("@annotation(com.longyi.admin.annotation.Logging)")
    public void pointCut(){}
    @After("pointCut()")
    public void recordLog(JoinPoint joinPoint){
        log.info("记录日志");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Logging logging = method.getAnnotation(Logging.class);
        LocalDateTime now = LocalDateTime.now();
        String record = logging.record();
        String type = logging.type();
        Log log = new Log();
        log.setRecord(record);
        log.setType(type);
        log.setUser(TokenUtil.getUsername());
        System.out.println(log);
        Integer flag=0;
        if(log.getUser()!=null){
            List<Log> logList = logService.lambdaQuery().eq(Log::getUser, log.getUser()).eq(Log::getRecord, log.getRecord()).eq(Log::getType, log.getType()).apply("DATE(create_time)=CURDATE()").list();
            if(logList.size()>0){
                for (Log log1 : logList){
                    if(log1.getCreateTime().isAfter(now.minusSeconds(3))){
                        System.out.println("重复记录");
                        flag=1;
                    }
                }

            }
            if(flag==0){
                logService.save(log);
            }
        }else {
            System.out.println("用户未登录");
        }
        
    }
}
